package com.example.rab.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.rab.annotation.PermissionAnnotation;
import com.example.rab.entity.domain.User;
import com.example.rab.entity.vo.LoginUserDetails;
import com.example.rab.mapper.UserMapper;
import com.example.rab.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @projectName: zzhMain
 * @package: com.example.rab.service.Impl
 * @className: UserServiceImpl
 * @author: zzh
 * @description: TODO
 * @version: 1.0
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        try {
            User user = userMapper.selectOne(wrapper);//这里要确保userName是唯一的
            //添加判断角色
            return new LoginUserDetails(user, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
        } catch (Exception e) {
            log.info("未找到该用户");
            return null;
        }
    }

    @PermissionAnnotation
    @Override
    public User insertUser(User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, user.getPhone());
        if (userMapper.selectCount(wrapper) == 0) {
            userMapper.insert(user);
            return user;
        } else {
            log.error("用户已存在");
            return null;
        }
    }
}
